import tool from "../../../utils/tool.js";
const app = getApp();
var url = app.getURL();

Page({
  data: {
    type: null,
    picker: ['失物招领', '生活闲谈', '校园表白'],
    tag:[
      {name:'日常吐槽',value:'1'},
      {name:'分享喜悦',value:'2'},
      {name:'校园时光',value:'3'},
      {name:'美好回忆',value:'4'},
      {name:'其他闲谈',value:'5'}
    ],
    imgList: [],
    photo:""
  },

  onLoad:function(options){
    let that = this;
    that.isLogin();//登录验证

    // 获取type
    that.setData({
      type:options.type-1
    })
  },

  // 设置节流，保险起见设置8s的执行周期
  getsubmit: tool.throttle(function (e){
    console.log('form发生了submit事件，携带的数据为：', e)
    this.submit(e);
  },8000),
  //提交表单
submit: function(e) {
  console.log('传递后form发生了submit事件，携带的数据为：', e.detail.value)

    var that = this;
    let tempFilePaths = this.data.imgList
    
    if (e.detail.value.content=='') {
      wx.showToast({
        title: '内容不能为空~',
        icon: "none",
        duration: 2000
      })
    }else {
      // 表白无需图片
      if(that.data.type==2){
        that.lovePublish(e)
      }
      if(this.data.imgList!=''){
        console.log("存在照片，上传照片中")
        wx.uploadFile({
          url: url+'/sysUse/sys/sysUse/oss/fileUpload',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'folder': 'userImg' 
          },
          success (res){
            var fi = JSON.parse(res.data)//转为对象使用
            console.log(fi)
            that.setData({
              photo: fi.data
            })
            wx.showToast({
              title: '图片上传成功',
              icon: 'success',
              duration: 1000
            })
          }
        })
      }
        console.log("直接上传")
        wx.showToast({
          title: '发布中',
          icon: 'loading',
          duration: 2000
        })
        // 手动设置延迟，防止图片未上传
        setTimeout(function () {
          if(that.data.type==0){
            // 失物招领发布
            that.lostPublish(e)
          }else if(that.data.type==1){
            // 校园闲谈发布
            that.talkPublish(e)
          }
        },3000)
          
      }
    
  },

  // 失物招领发布
  lostPublish(e){
    console.log(e)
    let that = this    
    let id = wx.getStorageSync('message').id
    wx.request({
      url: url+'/comm/app/comm/lostFound/auth/addLostFound',
      method: "POST",
      header: {// 设置请求的 header
        'content-type': 'application/json',
        token:wx.getStorageSync('cookieToken')
      },
      data:{
        "authorId": id,
        "content": e.detail.value.content,
        "photos": that.data.photo
      },
      success(res) {
        console.log(res.data.code)
        if(res.data.code==200){
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(function(){
            wx.switchTab({
              url: '../../index/index'
            })
          },1000)
        }else if(res.data.code==512){
          wx.showToast({
            title: '用户未认证',
            icon: 'error',
            duration: 1000
          })
          setTimeout(function(){
            wx.redirectTo({
                url: '/pages/my/user/message/message'
            })  
        },1500)
        }else{
          wx.showToast({
            title: '发布失败',
            icon: 'error',
            duration: 1000
          })
        }
      }
    })
  },
 // 校园闲谈发布
 talkPublish(e){
  console.log(e)
  let that = this    
  let id = wx.getStorageSync('message').id
  wx.request({
    url: url+'/comm/app/comm/topic/auth/addTopic',
    method: "POST",
    header: {// 设置请求的 header
      'content-type': 'application/json',
      token:wx.getStorageSync('cookieToken')
    },
    data:{
      "authorId": id,
      "topicContent": e.detail.value.content,
      "topicImage": that.data.photo,
      "topicType": e.detail.value.type
    },
    success(res) {
      console.log(res.data.code)
      if(res.data.code==200){
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(function(){
          wx.switchTab({
            url: '../../index/index'
          })
        },1000)
      }else if(res.data.code==512){
        wx.showToast({
          title: '用户未认证',
          icon: 'error',
          duration: 1000
        })
        setTimeout(function(){
          wx.redirectTo({
              url: '/pages/my/user/message/message'
          })  
      },1500)
      }else{
        wx.showToast({
          title: '发布失败',
          icon: 'error',
          duration: 1000
        })
      }
    }
  })
},
// 表白发布
lovePublish(e){
  console.log(e)
  let that = this    
  let id = wx.getStorageSync('message').id
  wx.request({
    url: url+'/comm/app/comm/expressWall/auth/insert',
    method: "POST",
    header: {// 设置请求的 header
      'content-type': 'application/json',
      token:wx.getStorageSync('cookieToken')
    },
    data:{
      "authorName": e.detail.value.fromName,
      "content": e.detail.value.content,
      "expressObj": e.detail.value.toName
    },
    success(res) {
      console.log(res.data.code)
      if(res.data.code==200){
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(function(){
          wx.switchTab({
            url: '../../index/index'
          })
        },1000)
      }else if(res.data.code==512){
        wx.showToast({
          title: '用户未认证',
          icon: 'error',
          duration: 1000
        })
        setTimeout(function(){
          wx.redirectTo({
              url: '/pages/my/user/message/message'
          })  
      },1500)
      }else{
        wx.showToast({
          title: '发布失败',
          icon: 'error',
          duration: 1000
        })
      }
    }
  })
},
    //判断是否登录，如果未登录的话就提示登录
    isLogin(){
      let that = this;
    //获取本地缓存的用户信息
   let user = app.getGlobalUserInfo();
      if(user.cookieNickname==null||user.cookieNickname==''){
        wx.showToast({
          title: "请先登录",
          icon: "none",
          duration: 2000
          })
          setTimeout(function(){
            wx.switchTab({
              url: '/pages/my/user/user'
            });
          },600)
        
      }
 },
 checkboxChange:function(e){
  console.log('你选中的项目有:'+e.detail.value);
  this.setData({
    tags:e.detail.value
  })
},

ChooseImage() {
  wx.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: (res) => {
      if (this.data.imgList.length != 0) {
        this.setData({
          imgList: this.data.imgList.concat(res.tempFilePaths)
        })
      } else {
        this.setData({
          imgList: res.tempFilePaths
        })
      }
    }
  });
},
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '',
      content: '确定要删除这张照片吗？',
      cancelText: '再看看',
      confirmText: '确认删除',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
})
